package com.yanqu.road.task;

import com.yanqu.road.connect.AgentServerConnectionGroup;
import com.yanqu.road.utils.ServerType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.ScheduledFuture;

public class ReconnectTask implements Runnable{
    private static Logger logger = LogManager.getLogger(ReconnectTask.class.getName());
    private ScheduledFuture<?> future = null;
    private AgentServerConnectionGroup serverConnectionGroup;

    public ReconnectTask(AgentServerConnectionGroup serverConnectionGroup) {
        this.serverConnectionGroup = serverConnectionGroup;
    }

    public void setFuture(ScheduledFuture<?> future) {
        this.future = future;
    }

    @Override
    public void run() {
        try {
                boolean result;
                if (noNeedCheckServer()) {
                    result = true;
                } else {
                    result = serverConnectionGroup.reConnect();
                }
                logger.info("重新连接 {} 服务器, ip地址: {}:{},result:{}", serverConnectionGroup.getServerName(), serverConnectionGroup.getIpAddress(), serverConnectionGroup.getPort(), result);
                if (result) {
                    future.cancel(true);
                    logger.info("重连成功:{}:{}" , serverConnectionGroup.getIpAddress() , serverConnectionGroup.getPort() );
                    return;
                }
        } catch (Exception e) {
            logger.error("重连异常:", e);
        }
    }

    private boolean noNeedCheckServer() {
        return serverConnectionGroup.getServerType() == ServerType.SERVER_CROSS
                || serverConnectionGroup.getServerType() == ServerType.SERVER_CROSS_2
                || serverConnectionGroup.getServerType() == ServerType.CENTER_CROSS_2
                || serverConnectionGroup.getServerType() == ServerType.BANQUET_CROSS;
    }
}
